﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace RapidTestMapMaker
{
    public class Tile
    {
        private const int SubTilesX = 5;
        private const int SubTilesY = 5;

        public Image this[int x, int y]
        {
            get { return subtiles[Common.plusMod(x, SubTilesX), Common.plusMod(y, SubTilesY)]; }
        }

        private Image[,] subtiles = new Image[SubTilesX, SubTilesY];

        public Image FullImage
        {
            get { return fullImage; }
            set
            {
                if (fullImage != value)
                {
                    fullImage = value;
                    SplitSubTiles();
                    if (TileChanged != null)
                    {
                        TileChanged(this, new EventArgs());
                    }
                }
            }
        }
        private Image fullImage;

        public event EventHandler<EventArgs> TileChanged;

        private void SplitSubTiles()
        {
            for (int x = 0; x < SubTilesX; x++)
            {
                for (int y = 0; y < SubTilesY; y++)
                {
                    if (subtiles[x, y] != null)
                    {
                        subtiles[x, y].Dispose();
                        subtiles[x, y] = null;
                    }

                }
            }
            if (fullImage == null)
            { return; }
            int w = fullImage.Width;
            int h = fullImage.Height;
            int sx = w / SubTilesX;
            int sy = h / SubTilesY;
            for (int x = 0; x < SubTilesX; x++)
            {
                for (int y = 0; y < SubTilesY; y++)
                {
                    Bitmap subtile = new Bitmap(sx, sy);
                    using (Graphics g = Graphics.FromImage(subtile))
                    {
                        int dx = -x;
                        int dy = -y;
                        g.DrawImage(fullImage, dx * sx, dy * sy);
                        g.Flush();
                        subtiles[x, y] = subtile;
                        subtile.Save("temp.png");
                    }
                }
            }
        }
    }
}
